var querystring = require("querystring"),
	fs = require("fs"),
	formidable = require("formidable"),
	util = require('util'),
	sqlite3 = require('sqlite3').verbose(),
	gcm = require('node-gcm');

var db = new sqlite3.Database('./test.db');

function start(response, request) {
	console.log("Request handler 'start' was called.");
	var body = '<html>' +
		'<head>' +
		'<meta http-equiv="Content-Type" ' +
		'content="text/html; charset=UTF-8" />' +
		'</head>' +
		'<body>' +
		'<form action="/register" method="post">' +
		'<input type="text" name="regId">' +
		'<input type="submit" value="Register ID" />' +
		'</form>' +
		'</body>' +
		'</html>';
	response.writeHead(200, {
		"Content-Type": "text/html"
	});
	response.write(body);
	response.end();
}

function register(response, request) {
	console.log("Request handler 'register' was called.");

	var form = new formidable.IncomingForm();

	form.parse(request, function(err, fields, files) {
		response.writeHead(200, {
			'content-type': 'text/plain'
		});

		db.serialize(function() {
			db.run("INSERT INTO andro_devices VALUES (?) ", fields.regId);
		});

		response.write('ID registered: ' + fields.regId + '\n\n');
		response.end();
	});
}

function show(response, request) {
	console.log("Request handler 'show' was called.");
	fs.readFile("/tmp/test.png", "binary", function(error, file) {
		if (error) {
			response.writeHead(500, {
				"Content-Type": "text/plain"
			});
			response.write(err + "\n");
			response.end();
		} else {
			response.writeHead(200, {
				"Content-Type": "image/png"
			});
			response.write(file, "binary");
			response.end();
		}
	});
}

function notify(response, request) {
	console.log("Request handler 'notify' was called");

	var retour = {};

	var respond = function() {
		var message = new gcm.Message();
		var sender = new gcm.Sender('AIzaSyAUxMqaXdW6vax2Qvf2FIO1n-z8XgzoOgM');
		var registrationIds = [];

		// Filling the IDs to broadcast the notification
		for (var i = 0; i < retour.length; i++) {
			var obj = retour[i];
			for (var key in obj) {
				if (key == "id_gcm")  {
					registrationIds.push('' + obj[key]);
				}
			}
		}
		
		// Optional
		message.addData('key1', 'message1');
		message.addData('key2', 'message2');
		message.collapseKey = 'demo';
		message.delayWhileIdle = true;
		message.timeToLive = 3;

		console.log(util.inspect(registrationIds));
		/**
		 * Parameters: message-literal, registrationIds-array, No. of retries, callback-function
		 */
		sender.send(message, registrationIds, 4, function(err, result) {
			console.log(result);
		});


		response.end(JSON.stringify(retour));
	}

	db.all("SELECT rowid,id_gcm FROM andro_devices", function(err, rows) {
		if (rows != undefined) {
			retour = rows;
		} else {
			retour['error'] = 'Error, could not fetch android devices data...';
			console.log(err);
		}
		respond();
	});

}
exports.start = start;
exports.register = register;
exports.show = show;
exports.notify = notify;

